namespace TomatoBreak.Infrastructure
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    public class FilterProvider : IFilterProvider
    {
        private readonly FilterRegistry registry;

        public FilterProvider(FilterRegistry registry)
        {
            if (registry == null)
            {
                throw new ArgumentNullException("registry");
            }

            this.registry = registry;
        }

        public virtual IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            var controllerFilters = BuildFilters(registry.FindControllerFilters(controllerContext, actionDescriptor), FilterScope.Controller);

            var actionFilters = BuildFilters(registry.FindActionFilters(controllerContext, actionDescriptor), FilterScope.Action);

            var combinedFilters = controllerFilters.Concat(actionFilters).ToList();

            return combinedFilters;
        }

        private static IEnumerable<Filter> BuildFilters(IEnumerable<FilterRegistryItem> filters, FilterScope scope)
        {
            return filters.SelectMany(i => i.Filters)
                          .Select(func => func())
                          .Select(f => new Filter(f, scope, null));
        }
    }
}